package ele_handler

import (
	"fmt"
	"go-yuque/yuque/extend"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &codeStruct{}
			h.elements = []string{"code"}
			return h
		})
}

type codeStruct struct {
	BaseHandler
	// tmpBuffer *strings.Builder `name:"临时保存textContext"`
	extend.BufferStruct
}

func (c *codeStruct) preHandle() error {
	// // 用临时缓冲区替换 textContext
	// c.tmpBuffer = &strings.Builder{}
	// c.tmpBuffer = *c.textContentP
	// // 创建新的 textContentP
	// sbP := &strings.Builder{}
	// *c.BaseHandler.textContentP = sbP

	c.ChangeToBuffer(c.textContentP)

	c.ctxMap["wrapCode"] = true

	// c.WriteTextContext("`")
	return nil
}

func (c *codeStruct) postHandle() error {

	delete(c.ctxMap, "wrapCode")

	hasSpanStyle := c.ctxMap["hasSpanStyle"]
	if hasSpanStyle != nil && hasSpanStyle.(bool) {
		// 被 code 包裹下的 span 存在样式，就不需要使用 `` 包裹了
		// c.tmpBuffer.WriteString((*c.textContentP).String())
		c.WriteInBuffer((*c.textContentP).String())
		delete(c.ctxMap, "hasSpanStyle")
	} else {
		// c.tmpBuffer.WriteString(fmt.Sprintf("`%s`", (*c.textContentP).String()))
		c.WriteInBuffer(fmt.Sprintf("`%s`", (*c.textContentP).String()))
	}

	// 换回来
	c.RecoverFromBuffer(c.textContentP)

	return nil
}
